package com.mineapp.base

import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.text.TextUtils
import android.view.*
import android.widget.LinearLayout
import com.tool.Lifecycle
import com.common.R
import com.mineapp.weight.LoadingDialog
import com.mineapp.weight.ToolbarView
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

/**
 *
 * Created by mac on 2017/7/31.
 */
open class BaseActivity : AppCompatActivity() {
    var mCurrentTag: String? = ""
    var mToolbar: Toolbar? = null
    var mContentView: LinearLayout? = null
    var mToolbarView: ToolbarView? = null
    var mLifecycle: Lifecycle? = null
    var mRetrofit: Retrofit? = null
    val mLoadingDialog: LoadingDialog by lazy {
        LoadingDialog(this)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mLifecycle?.onCreate(savedInstanceState)
        mRetrofit = Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl("http://172.16.0.146:10008")
                .build()
        initContentView()
    }

    override fun onResume() {
        super.onResume()
        mLifecycle?.onResume()
    }

    private fun initContentView() {
        mContentView = LinearLayout(this)
        val layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT)
        mContentView?.layoutParams = layoutParams
        mContentView?.orientation = LinearLayout.VERTICAL
        if(mContentView != null) {
            super.setContentView(mContentView)
        }
    }

    override fun setContentView(layoutResID: Int) {
        val contentView = LayoutInflater.from(this).inflate(layoutResID, null)
        setContentView(contentView)
    }

    override fun setContentView(view: View?) {
        setContentView(view, view?.layoutParams)
    }

    override fun setContentView(view: View?, params: ViewGroup.LayoutParams?) {
        if(view == null) return
        initToolbar()
        if(view?.layoutParams == null) {
            val layoutParams = ViewGroup.MarginLayoutParams(ViewGroup.MarginLayoutParams.MATCH_PARENT,
                    ViewGroup.MarginLayoutParams.MATCH_PARENT)
            view.layoutParams = layoutParams
        }
        mContentView?.addView(view)
    }

    private fun initToolbar() {
        if(showToolbar()) {
            mToolbarView = ToolbarView(this)
            mToolbar = mToolbarView?.mToolbar
            if(mToolbar != null && mContentView?.indexOfChild(mToolbarView)!! < 0) {
                (mToolbarView?.parent as? ViewGroup)?.removeView(mToolbarView)
                mContentView?.addView(mToolbarView, 0)
                mToolbar?.setBackgroundColor(Color.parseColor("#3399ff"))
                mToolbar?.setNavigationIcon(R.mipmap.ic_back_white)
                mToolbar?.setNavigationOnClickListener {
                    pop()
                }
            }
        }
    }

    open fun showToolbar(): Boolean {
        return true
    }

    fun setLifecycle(lifecycle: Lifecycle?) {
        mLifecycle = lifecycle
    }

    fun setMenu(res: Int) {
        mToolbar?.inflateMenu(res)
        mToolbar?.setOnMenuItemClickListener { item: MenuItem? ->
            onMenuItemClick(item)
            return@setOnMenuItemClickListener true
        }
    }

    open fun onMenuItemClick(item: MenuItem?) {

    }

    fun setTitle(title: String?) {
        mToolbarView?.setTitle(title)
    }

    fun startActivity(cls: Class<out Activity>?) {
        startActivity(cls, null)
    }

    fun startActivity(cls: Class<out Activity>?, bundle: Bundle? = null) {
        val intent = Intent(this, cls)
        if(bundle != null) {
            intent.putExtras(bundle)
        }
        startActivity(intent)
    }

    fun push(cls: Class<out Fragment>?, bundle: Bundle? = null) {
        if(cls == null || cls?.name.equals(mCurrentTag)) return
        val manager = supportFragmentManager
        val transaction = manager.beginTransaction()
        var target: Fragment? = manager.findFragmentByTag(cls.name)
        if(!TextUtils.isEmpty(mCurrentTag)) {
            val fragment = manager.findFragmentByTag(mCurrentTag)
            if (fragment?.isAdded!!) {
                transaction.hide(fragment)
            }
        }
        if(target != null) {
            target.arguments?.clear()
            transaction.show(target)
        } else {
            target = cls?.newInstance()
            transaction.add(containerId(), target, cls?.name)
            transaction.addToBackStack(cls?.name)
        }
        if(bundle != null) {
            target?.arguments = bundle
        }
        transaction.commit()
        mCurrentTag = cls?.name
    }

    fun addFragment(fragment: Fragment) {
        val manager = supportFragmentManager
        val transaction = manager.beginTransaction()
        transaction.add(containerId(), fragment, fragment.javaClass.name)
        transaction.addToBackStack(fragment.javaClass.name)
        transaction.commit()
    }

    fun pop() {
        if(supportFragmentManager.backStackEntryCount > 1) {
            supportFragmentManager.popBackStackImmediate()
            val fragment = supportFragmentManager.findFragmentByTag(supportFragmentManager.
                    getBackStackEntryAt(supportFragmentManager.backStackEntryCount - 1).name)
            mCurrentTag = fragment.javaClass.name
            if(fragment != null && fragment is BaseFragment) {
                fragment.hideActivityTitle()
            }
            return
        }
        finish()
    }

    open fun containerId(): Int {
        return 0
    }

    override fun onBackPressed() {
        pop()
    }

    override fun onDestroy() {
        mLoadingDialog.dismiss()
        super.onDestroy()
        mLifecycle?.onDestroy()

    }

    fun showLoading() {
        if (!mLoadingDialog.isShowing && !isFinishing) {
            mLoadingDialog?.show()
        }
    }

    fun hideLoading() {
        mLoadingDialog?.dismiss()
    }


}